import { defineStore } from 'pinia';
import * as systemApi from '@/api/system';
import { Message } from '@arco-design/web-vue';
import { ref } from 'vue';
import { get } from 'lodash';

const useSystemStore = defineStore('system', () => {
    const areas = ref<any>([])
    const settings = ref<any>([])

    function getAreaName(id: number) {
        return areas.value.find((item: any) => item.id === id)?.name
    }

    async function getAreas(param?: any) {
        const response: any = await systemApi.queryAreaList(param)
        if (response.code === 20000) {
            areas.value = response.data.areas
            return response.data.areas
        }
        return []
    }

    async function deleteArea(param: { id?: number }) {
        const response: any = await systemApi.deleteArea(param)
        if (response.code === 20000) {
            Message.success('移除成功');
        }
    }

    async function saveArea(param: any) {
        if (param.id) {
            await systemApi.updateArea(param);
        } else {
            await systemApi.createArea(param);
        }
        Message.success('保存成功');
    }

    async function getSettings() {
        if (settings.value.length > 0) {
            return settings.value;
        }
        const response: any = await systemApi.querySettingList()
        if (response.code === 20000) {
            settings.value = response.data.settings
        }
    }

    async function saveSettings() {
        const response: any = await systemApi.updateSettings(settings.value)
        if (response.code === 20000) {
            Message.success('保存成功');
        }
    }

    function getValue(groupCode: string, code: string) {
        return settings.value.find((item: any) => item.groupCode === groupCode && item.code === code)?.value
    }

    return { areas, getAreas, deleteArea, saveArea, getAreaName, settings, getSettings, saveSettings, getValue }
});

export default useSystemStore;
